const fs = require('fs');
const path = require('path');
const multer = require('multer');
const { successCode, errorCode } = require('../config/config.js');
// const upload = multer();

/**
 * 上传文件
 * @param {Object} formData 上传的文件
 * @param {object} [option] 上传的文件配置
 * @param {String} [option.FilePath] 上传文件的路径
 * @param {String} [option.fileName] 上传文件的名称
 * @param {Function} callback 回调函数
 * */
function uploadFile(formData, option, callback) {
    let { FilePath, fileName } = option;
    FilePath = FilePath ? path.resolve(__dirname, `${FilePath}`) : path.resolve(__dirname, '../upload/file');
    checkDirExist(FilePath);
    let storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, FilePath);
        },
        filename: function (req, file, cb) {
            // let suffix = file.mimetype.split('/')[1]; //获取文件格式
            let suffix = file.originalname.match(/[^.]+$/)[0]; //获取文件格式
            
            if (fileName) {
                cb(null, fileName + '-' + Date.now() + '.' + suffix);
                return;
            }
            fileName = 'file' + '-' + Date.now() + '.' + suffix;
            cb(null, fileName);
            // cb(null, file.originalname);
        },
    });
    let upload = multer({ storage: storage }).single('file');
    upload.file = function(req,res){
        console.log("body ==>" , req.body)
    }
    upload(formData, null, function (err) {

        if (err) {
            console.log("err =>" , err)
            callback({
                ...errorCode[10006],
                err,
            });
        } else {
            callback({
                ...successCode[200],
                data: {
                    fileName: fileName,
                },
            });
        }
    });

}

/**判断目录是否存在 不存在在创建目录*/
function checkDirExist(filePath) {
    if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath);
    }
    try {
        fs.accessSync(filePath);
    } catch (error) {
        rfs.mkdirSync(filePath);
    }
}

/**
 * @name 删除文件
 * @param {object} option 删除文件配置
 * @param {string} option.filePath 文件路径
 * @param {string} [option.fileName] 文件名
 * @param {boolean} [option.is_delete_dir] 是否删除目录
 * @param {Function} [option.success] 成功回调
 * @param {Function} [option.fail] 失败回调
 * */
function deleteFile(option) {
    const options = {
        filePath: '', //文件路径
        fileName: '', //文件名
        is_delete_dir: false, //是否删除目录
        success: () => { }, //成功回调
        fail: () => { }, //失败回调
    }
    Object.assign(options, option);
    const { filePath, fileName, is_delete_dir, success, fail } = options;
    if(!filePath){
        fail({
            ...errorCode[10001],
            err: 'filePath or fileName is not defined',
        });
        return;
    }
    if(!fs.existsSync(filePath)){
        fail({
            ...errorCode[10001],
            err: 'filePath is not exist',
        });
        return;
    }
    const file = path.resolve(__dirname, filePath, fileName);
    fs.unlink(file, (err) => {
        if (err) {
            fail({
                ...errorCode[10008],
                err,
            });
            return;
        }
        if (is_delete_dir) {
            fs.rmdir(filePath, (err) => {
                if (err) {
                    error(err);
                    return;
                }
                success(successCode[200]);
            });
        } else {
            success(successCode[200]);
        }
    });
}

/**
 * 上传文件
 * @param {Array} files 文件列表 带有buffer的
 * @param {Object} option 配置信息
 * @param {String} [option.FilePath] 上传文件的路径
 * @param {String} [option.fileName] 上传文件的名称
 * @param {Function} [option.success] 成功回调
 * @param {Function} [option.fail] 失败回调
 * @param {Function} [callback] 回调函数
 * */ 
const uploads = (files , option , callback) =>{
    let options = {
        FilePath: '../upload/file',
        fileName: '',
        success: () => { },
        fail: () => { },
    }
    Object.assign(options, option);
    options.FilePath = path.resolve(__dirname, options.FilePath);
    if(!files){
        options.fail({
            ...errorCode[10001],
            err: 'files is not defined',
        });
        throw Error("files is not defined")
    }
    let count = files.length;
    let fileInfo = [];
    files.forEach(file => {
        let suffix = file.originalname.match(/[^.]+$/)[0]; //获取文件格式
        options.fileName = options.fileName ? options.fileName + '.' + suffix : 'file' + '-' + Date.now() + '.' + suffix;
        try {
            fs.writeFileSync(options.FilePath + '/' + options.fileName, file.buffer);
            fileInfo.push({
                fileName: options.fileName,
            });
            count--;
            if(count == 0){
                options.success({
                    ...successCode[200],
                    data: fileInfo,
                });
                callback && callback({
                    ...successCode[200],
                    data: fileInfo,
                });
            }
        }catch(err){
            options.fail({
                ...errorCode[10006],
                err,
            });
            callback && callback({
                ...errorCode[10006],
                err,
            });
        }
    });
}

module.exports = {
    uploadFile,
    deleteFile,
    uploads
};